<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片 --> 
         <el-card>
            <el-alert title="添加商品信息" type="info" show-icon center :closable='false'>
            </el-alert>
            <!-- 步骤条 -->
            <el-steps :space="200" :active="activeindex-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
            </el-steps>
            <!-- tab标签 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position='top'>
                <el-tabs :tab-position="'left'" v-model="activeindex" :before-leave='beforeTab' @tab-click='tabClick'>
                    <el-tab-pane label="基本参数" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="">
                             <!-- 级联选择器 -->
                             <!-- options 数据源 -->
                             <!-- v-model 选中的类容-->
                              <el-cascader
                                v-model="addForm.goods_cat"
                                :options="cateList"
                                :props="{ 
                                    expandTrigger: 'hover' ,
                                    value:'cat_id',
                                    label:'cat_name',
                                    children:'children'
                                    }"
                                @change="handleChange">
                              </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="item in getMany" :key="item.attr_id">
                            <!-- 多选框 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="item2" v-for="(item2,i) in item.attr_vals" :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in getOnly" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- action 上传的路径 -->
                        <!-- :on-preview 点击预览图片触发函数-->
                        <!-- :on-remove 点击删除按钮触发函数-->
                        <!-- list-type="picture" 默认以缩略图效果展示 -->
                        <!-- headers 设置请求头-->
                        <!-- :on-success 上传成功执行的函数-->
                        <el-upload
                        :action="basUrl"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture"
                        :headers='headersObj'
                        :on-success='handleSuccess'
                        >
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器 -->
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                        <el-button type="primary" class="addBtn" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览对话框        -->
        <el-dialog
        title="图片预览"
        :visible.sync="showPreview"
        width="50%">
        <img :src="preview" alt="" class="imgSize">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'
export default {
    data () {
        return {
            //默认步骤
           activeindex:'0',
           //表单数据
           addForm:{
              goods_name:'',
              goods_price:'0',
              goods_weight:'0',
              goods_number:'0',
              goods_cat:[],
              //图片的数组
              pics:[],
              //富文本类容
              goods_introduce:'',
              //商品的参数
              attrs:[]
           },
           //表单效验规则
           addFormRules:{
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }
                ],
                goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                ],                 
                goods_number: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' }
                ]                                
           },
           //商品分类数据
            cateList:[],
            //商品动态数据参数
            getMany:[],
            //商品静态数据参数
            getOnly:[],
            //设置上传路径
            basUrl:'http://127.0.0.1:8888/api/private/v1/upload',
            //设置图片的请求头
            headersObj:{
                Authorization: window.sessionStorage.getItem('token')
            },
            //图片预览路径
            preview:'',
            //图片预览默认状态
            showPreview:false
        }
    },
    created () {
       this.getAddList()
    },
    methods:{
      async getAddList () {
           const res = await this.$http.get('categories')
           if(res.data.meta.status){
              this.cateList = res.data.data
           }else{
               this.$message.success('获取商品分类失败');
           }
       },
       //级联选择器发生改变触发的函数
       handleChange () {
           //设置只能选中3级分类
            if(this.addForm.goods_cat.length !==3){
                this.addForm.goods_cat = []
            }
           console.log(this.addForm.goods_cat)
       },
       beforeTab (activeName,oldActiveName) {
            // activeName 即将进入的标签页
            // oldActiveName 即将离开的标签页
            if(this.addForm.goods_cat.length !== 3 && oldActiveName === '0'){
               this.$message.error('请选择商品分类');
               return false
            }
       },
      async tabClick () {
          if(this.activeindex ==='1'){
             const res = await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:'many'}})
             if(res.data.meta.status == 200){
                 res.data.data.forEach(item=>{
                     item.attr_vals = item.attr_vals.length === 0 ? [] :item.attr_vals.split(',')
                 })
                 this.getMany = res.data.data
                 console.log(this.getMany)
             }else{
                  this.$message.error('获取商品动态参数失败');
             }
          }else if(this.activeindex === '2'){
              const res = await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:'only'}})
              if(res.data.meta.status == 200){
                  this.getOnly = res.data.data
                  console.log(this.getOnly)
              }else{
                  this.$message.error('获取商品静态参数失败');
              }
          }
       },
       //点击图片预览函数
       handlePreview (file) {
           console.log(file)
           //1保存要预览的路径
           this.preview = file.response.data.url
           //点击后打开对话框
           this.showPreview = true
       },
      //点击删除图片函数
       handleRemove (file) {
         console.log(file)
         //1.获取要删除的路径这里函数的参数就是
           const filePath = file.response.data.tmp_path
         //2.从 pics中找到这个图片的索引findIndex()方法可以返回对应的index值
          const i = this.addForm.pics.findIndex(v=>{
               v.pic === filePath
           })
         //3.调用数组splice方法把图片从pics中删除
          this.addForm.pics.splice(i,1)
       },
       //上传成功执行的钩子函数
       handleSuccess (response) {
           console.log(response)
          const picInfo = {pic: response.data.tmp_path}
         this.addForm.pics.push(picInfo)
          console.log(this.addForm)
       },
       //最终的添加
       add () {
           this.$refs.addFormRef.validate(async valid=>{
               if(!valid){
                    return this.$message.error('请填写表单必要项');
               }else{
                  //这里级联选择器和接口文档一个要求是数组一个要求是字符串所以要用深拷贝
                  //让级联选择器还是用原来的数据，而传接口的用拷贝后的
                  //cloneDeep(obj)这是深拷贝的方法
                  const form = _.cloneDeep(this.addForm)
                  form.goods_cat = form.goods_cat.join(',')
                  //动态参数
                  this.getMany.forEach(item=>{
                     const newinfor = {
                        attr_id:item.attr_id,
                        attr_value:item.attr_vals.join(' ')
                     }
                     this.addForm.attrs.push(newinfor)
                  })
                  //静态参数
                  this.getOnly.forEach(item=>{
                      const newinfor = {
                          attr_id:item.attr_id,
                          attr_value:item.attr_vals
                      }
                      this.addForm.attrs.push(newinfor)
                  })
                  form.attrs = this.addForm.attrs
                  console.log(form)
                  const res = await this.$http.post('goods',form)
                  if(res.data.meta.status == 201){
                     this.$message.success('添加成功')
                     this.$router.push('/goods')
                  }else{
                       return this.$message.error('添加失败');
                  }
               }
           })
       }
    },
    computed:{
       cateID () {
           if(this.addForm.goods_cat.length ===3){
              return this.addForm.goods_cat[2]
           }else{
               return null
           }
       }
    }
}
</script>

<style lang="less" scoped>
   .el-checkbox{
       margin: 0 10px 0 0 !important;
   }
   .imgSize{
       width: 100%;
   }
   .addBtn{
       margin: 20px 0;
   }
</style>